import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Button,
  Chip,
  Tooltip,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  TextField,
  InputAdornment,
  ToggleButton,
  ToggleButtonGroup,
  Stack,
  Menu,
  MenuItem,
} from '@mui/material';
import {
  Add as AddIcon,
  Refresh as RefreshIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  PlayArrow as PlayIcon,
  Stop as StopIcon,
  Warning as WarningIcon,
  CheckCircle as CheckCircleIcon,
  Search as SearchIcon,
  MoreVert as MoreVertIcon,
  SettingsEthernet as ConnectionIcon,
} from '@mui/icons-material';
import { useConnectionStore } from '../../stores/connectionStore';

const ConnectionList: React.FC = () => {
  const navigate = useNavigate();
  const {
    connections,
    loading,
    error,
    fetchConnections,
    deleteConnection,
    setCurrentConnection,
    reconnectConnection,
    reconnectAllConnections,
    checkConnectionHealth,
  } = useConnectionStore();

  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'connected' | 'disconnected'>('all');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedConnection, setSelectedConnection] = useState<string | null>(null);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [menuConnection, setMenuConnection] = useState<string | null>(null);
  const [healthStatus, setHealthStatus] = useState<Record<string, boolean>>({});

  useEffect(() => {
    console.log('ConnectionList: 开始获取连接数据');
    fetchConnections();
  }, [fetchConnections]);

  // 监听连接数据变化
  useEffect(() => {
    console.log('ConnectionList: 连接数据更新', connections);
    console.log('ConnectionList: 连接数量', connections?.length || 0);
  }, [connections]);

  useEffect(() => {
    // 检查所有连接的健康状态
    const checkHealth = async () => {
      const status: Record<string, boolean> = {};
      for (const conn of connections) {
        try {
          const isHealthy = await checkConnectionHealth(conn.name);
          status[conn.name] = isHealthy;
        } catch (error) {
          status[conn.name] = false;
        }
      }
      setHealthStatus(status);
    };

    if (connections.length > 0) {
      checkHealth();
    }
  }, [connections, checkConnectionHealth]);

  const handleCreateConnection = () => {
    navigate('/connections/create');
  };

  const handleDeleteConnection = (connectionId: string) => {
    setSelectedConnection(connectionId);
    setDeleteDialogOpen(true);
  };

  const confirmDeleteConnection = async () => {
    if (selectedConnection) {
      try {
        await deleteConnection(selectedConnection);
        setDeleteDialogOpen(false);
        setSelectedConnection(null);
      } catch (error) {
        console.error('删除连接失败:', error);
      }
    }
  };

  const handleSetCurrentConnection = async (connectionId: string) => {
    try {
      await setCurrentConnection(connectionId);
    } catch (error) {
      console.error('设置当前连接失败:', error);
    }
  };

  const handleReconnectConnection = async (connectionId: string) => {
    try {
      await reconnectConnection(connectionId);
    } catch (error) {
      console.error('重新连接失败:', error);
    }
  };

  const handleReconnectAll = async () => {
    try {
      await reconnectAllConnections();
    } catch (error) {
      console.error('重新连接所有连接失败:', error);
    }
  };

  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>, connectionId: string) => {
    setAnchorEl(event.currentTarget);
    setMenuConnection(connectionId);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
    setMenuConnection(null);
  };

  const filteredConnections = connections.filter((conn) => {
    const matchesSearch = conn.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         conn.uri.toLowerCase().includes(searchTerm.toLowerCase());
    
    if (statusFilter === 'all') return matchesSearch;
    if (statusFilter === 'connected') return matchesSearch && conn.connected;
    if (statusFilter === 'disconnected') return matchesSearch && !conn.connected;
    
    return matchesSearch;
  });

  const getConnectionStatusColor = (connected: boolean) => {
    return connected ? 'success' : 'error';
  };

  const getConnectionStatusText = (connected: boolean) => {
    return connected ? '已连接' : '未连接';
  };

  const getHealthStatusIcon = (connectionName: string) => {
    const isHealthy = healthStatus[connectionName];
    if (isHealthy === undefined) return null;
    
    return isHealthy ? (
      <Tooltip title="连接健康">
        <CheckCircleIcon color="success" fontSize="small" />
      </Tooltip>
    ) : (
      <Tooltip title="连接异常">
        <WarningIcon color="warning" fontSize="small" />
      </Tooltip>
    );
  };

  return (
    <Box>
      {/* 页面标题和操作栏 */}
      <Box sx={{ mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h4" component="h1" fontWeight="bold">
            连接管理
          </Typography>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={<RefreshIcon />}
              onClick={handleReconnectAll}
              disabled={loading}
            >
              全部重连
            </Button>
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={handleCreateConnection}
            >
              创建连接
            </Button>
          </Box>
        </Box>

        {/* 搜索和过滤栏 */}
        <Stack direction="row" spacing={2} sx={{ mb: 2 }}>
          <TextField
            placeholder="搜索连接名称或URI..."
            variant="outlined"
            size="small"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
            sx={{ flex: 1, maxWidth: 400 }}
          />
          <ToggleButtonGroup
            value={statusFilter}
            exclusive
            onChange={(_, value) => setStatusFilter(value || 'all')}
            size="small"
          >
            <ToggleButton value="all">全部</ToggleButton>
            <ToggleButton value="connected">已连接</ToggleButton>
            <ToggleButton value="disconnected">未连接</ToggleButton>
          </ToggleButtonGroup>
        </Stack>
      </Box>

      {/* 错误提示 */}
      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => useConnectionStore.getState().clearError()}>
          {error}
        </Alert>
      )}

      {/* 连接列表 */}
      <TableContainer component={Paper} variant="outlined">
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>状态</TableCell>
              <TableCell>连接名称</TableCell>
              <TableCell>URI</TableCell>
              <TableCell>主机名</TableCell>
              <TableCell>版本</TableCell>
              <TableCell align="center">健康状态</TableCell>
              <TableCell align="center">操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={7} align="center">
                  <CircularProgress size={24} />
                </TableCell>
              </TableRow>
            ) : filteredConnections.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} align="center">
                  <Box sx={{ py: 4, textAlign: 'center' }}>
                    <ConnectionIcon sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
                    <Typography variant="h6" color="text.secondary" gutterBottom>
                      暂无连接
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {searchTerm || statusFilter !== 'all' 
                        ? '没有找到匹配的连接' 
                        : '点击"创建连接"按钮添加您的第一个连接'}
                    </Typography>
                  </Box>
                </TableCell>
              </TableRow>
            ) : (
              filteredConnections.map((connection) => (
                <TableRow key={connection.name} hover>
                  <TableCell>
                    <Chip
                      label={getConnectionStatusText(connection.connected)}
                      color={getConnectionStatusColor(connection.connected)}
                      size="small"
                      variant="filled"
                    />
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Typography variant="body2" fontWeight="medium">
                        {connection.name}
                      </Typography>
                      {useConnectionStore.getState().currentConnection === connection.name && (
                        <Chip label="默认" size="small" color="primary" variant="outlined" />
                      )}
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" color="text.secondary" sx={{ fontFamily: 'monospace' }}>
                      {connection.uri}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {connection.hostname || '-'}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {connection.version || '-'}
                    </Typography>
                  </TableCell>
                  <TableCell align="center">
                    {getHealthStatusIcon(connection.name)}
                  </TableCell>
                  <TableCell align="center">
                    <Box sx={{ display: 'flex', gap: 0.5, justifyContent: 'center' }}>
                      <Tooltip title="设为默认连接">
                        <IconButton
                          size="small"
                          onClick={() => handleSetCurrentConnection(connection.name)}
                          color={useConnectionStore.getState().currentConnection === connection.name ? 'primary' : 'default'}
                        >
                          <ConnectionIcon fontSize="small" />
                        </IconButton>
                      </Tooltip>
                      
                      {!connection.connected ? (
                        <Tooltip title="重新连接">
                          <IconButton
                            size="small"
                            onClick={() => handleReconnectConnection(connection.name)}
                            color="success"
                          >
                            <PlayIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      ) : (
                        <Tooltip title="断开连接">
                          <IconButton
                            size="small"
                            color="error"
                            disabled
                          >
                            <StopIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      )}
                      
                      <IconButton
                        size="small"
                        onClick={(event) => handleMenuOpen(event, connection.name)}
                      >
                        <MoreVertIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 更多操作菜单 */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
      >
        <MenuItem onClick={handleMenuClose}>
          <EditIcon fontSize="small" sx={{ mr: 1 }} />
          编辑
        </MenuItem>
        <MenuItem 
          onClick={() => {
            if (menuConnection) {
              handleDeleteConnection(menuConnection);
            }
            handleMenuClose();
          }}
          sx={{ color: 'error.main' }}
        >
          <DeleteIcon fontSize="small" sx={{ mr: 1 }} />
          删除
        </MenuItem>
      </Menu>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>确认删除连接</DialogTitle>
        <DialogContent>
          <DialogContentText>
            您确定要删除连接 "{selectedConnection}" 吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button onClick={confirmDeleteConnection} color="error" variant="contained">
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ConnectionList;